﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DatNuocViet.Models;
using DatNuocViet.Ultility;
using ImageResizer;

namespace DatNuocViet.Areas.Admin.Controllers
{
    public class AdminHomeController : Controller
    {
        //
        // GET: /Admin/Home/

        #region changepass
        [CustomAuthentication]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult ChangePassword(FormCollection form)
        {
            string OldPass = form["OldPass"];
            string NewPass = form["NewPass"].Trim();
            string RetypePass = form["RetypePass"].Trim();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                if (OldPass != db.GetWebResource("datnuocviet.password").FirstOrDefault().ValueVn)
                {
                    ViewBag.message = "Mật khẩu cũ không đúng";
                    return View();
                }
                if (NewPass.Length < 6)
                {
                    ViewBag.message = "Mật khẩu phải lớn hơn 6 kí tự";
                    return View();
                }
                if (NewPass != RetypePass)
                {
                    ViewBag.message = "Mật xác nhận không trùng khớp";
                    return View();
                }
                db.UpdateWebResource("datnuocviet.password", NewPass, NewPass);
                ViewBag.message = "Thay đổi mật khẩu thành công";
                return View();
            }
        }
        #endregion

        #region aboutus
        [CustomAuthentication]
        public ActionResult Index()
        {
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.aboutus").FirstOrDefault();
            }
            return View(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult UpdateAboutUs(FormCollection form)
        {
            string Key = form["key"];
            string AboutUsVn = form["DescriptionVn"];
            string AboutUsEn = form["DescriptionEn"];
            if (string.IsNullOrEmpty(AboutUsVn))
            {
                AboutUsVn = "Chưa có thông tin";
            }
            if(string.IsNullOrEmpty(AboutUsEn))
            {
                AboutUsEn = "No information";
            }
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.UpdateWebResource(Key, HttpUtility.HtmlDecode(AboutUsVn), HttpUtility.HtmlDecode(AboutUsEn));
            }
            ViewBag.message = "Đã cập nhật thông tin công ty";
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.aboutus").FirstOrDefault();
            }
            return View("Index", model);
        }
        #endregion

        #region event
        [CustomAuthentication]
        public ActionResult Event()
        {
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.event").FirstOrDefault();
            }
            return View(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult UpdateEvent(FormCollection form)
        {
            string Key = form["key"];
            string AboutUsVn = form["DescriptionVn"];
            string AboutUsEn = form["DescriptionEn"];
            if (string.IsNullOrEmpty(AboutUsVn))
            {
                AboutUsVn = "Chưa có thông tin";
            }
            if (string.IsNullOrEmpty(AboutUsEn))
            {
                AboutUsEn = "No information";
            }
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.UpdateWebResource(Key, HttpUtility.HtmlDecode(AboutUsVn), HttpUtility.HtmlDecode(AboutUsEn));
            }
            ViewBag.message = "Đã cập nhật thông tin tổ chức sự kiện";
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.event").FirstOrDefault();
            }
            return View("Event", model);
        }
        #endregion

        #region service
        [CustomAuthentication]
        public ActionResult Service()
        {
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.service").FirstOrDefault();
            }
            return View(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult UpdateService(FormCollection form)
        {
            string Key = form["key"];
            string AboutUsVn = form["DescriptionVn"];
            string AboutUsEn = form["DescriptionEn"];
            if (string.IsNullOrEmpty(AboutUsVn))
            {
                AboutUsVn = "Chưa có thông tin";
            }
            if (string.IsNullOrEmpty(AboutUsEn))
            {
                AboutUsEn = "No information";
            }
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.UpdateWebResource(Key, HttpUtility.HtmlDecode(AboutUsVn), HttpUtility.HtmlDecode(AboutUsEn));
            }
            ViewBag.message = "Đã cập nhật thông tin dịch vụ";
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.service").FirstOrDefault();
            }
            return View("Service", model);
        }
        #endregion

        #region contact
        [CustomAuthentication]
        public ActionResult Contact()
        {
            GetWebResourceResult model = new GetWebResourceResult();
            GetWebResourceResult model1 = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.contact").FirstOrDefault();
                model1 = db.GetWebResource("datnuocviet.map").FirstOrDefault();
            }
            ViewBag.Map = model1.ValueVn;
            return View(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult UpdateContact(FormCollection form)
        {
            string Key = form["key"];
            string AboutUsVn = form["DescriptionVn"];
            string AboutUsEn = form["DescriptionEn"];
            string Map = form["map"];
            if (string.IsNullOrEmpty(AboutUsVn))
            {
                AboutUsVn = "Chưa có thông tin";
            }
            if (string.IsNullOrEmpty(AboutUsEn))
            {
                AboutUsEn = "No information";
            }
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.UpdateWebResource(Key, HttpUtility.HtmlDecode(AboutUsVn), HttpUtility.HtmlDecode(AboutUsEn));
                db.UpdateWebResource("datnuocviet.map", Map, Map);
            }
            ViewBag.message = "Đã cập nhật thông tin liên hệ";
            GetWebResourceResult model = new GetWebResourceResult();
            GetWebResourceResult model1 = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.contact").FirstOrDefault();
                model1 = db.GetWebResource("datnuocviet.map").FirstOrDefault();
            }
            ViewBag.Map = model1.ValueVn;
            return View("Contact", model);
        }
        #endregion

        #region login
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection form)
        {
            string name = form["Account"];
            string pass = form["Password"];
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                if (name == db.GetWebResource("datnuocviet.account").FirstOrDefault().ValueVn && pass == db.GetWebResource("datnuocviet.password").FirstOrDefault().ValueVn)
                {
                    HttpCookie hc = new HttpCookie("IsLoggin", "true");
                    hc.Expires = DateTime.Now.AddHours(2);
                    HttpContext.Response.SetCookie(hc);
                    return Content("<script type='text/javascript'>alert('Đăng nhập thành công');window.location.replace('/Admin/AdminHome');</script>");
                }
                else
                {
                    return Content("<script type='text/javascript'>alert('Tên đăng nhập hoặc mật khẩu không đúng');window.location.replace('/Admin/AdminHome/Login');</script>");
                }
            }
        }

        public ActionResult LogOut()
        {
            HttpCookie hc = new HttpCookie("IsLoggin", "true");
            hc.Expires = DateTime.Now.AddHours(-1);
            HttpContext.Response.SetCookie(hc);
            return Redirect(Url.Content("~"));
        }
        #endregion

        #region trian
        [CustomAuthentication]
        public ActionResult TriAn()
        {
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.trian").FirstOrDefault();

                ViewBag.commnentList = db.Comments.Where(p => p.isDelete != true).ToList();
            }

            return View(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public ActionResult UpdateTriAn(FormCollection form)
        {
            string Key = form["key"];
            string AboutUsVn = form["DescriptionVn"];
            string AboutUsEn = form["DescriptionEn"];
            if (string.IsNullOrEmpty(AboutUsVn))
            {
                AboutUsVn = "Chưa có thông tin";
            }
            if (string.IsNullOrEmpty(AboutUsEn))
            {
                AboutUsEn = "No information";
            }
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.UpdateWebResource(Key, HttpUtility.HtmlDecode(AboutUsVn), HttpUtility.HtmlDecode(AboutUsEn));
            }
            ViewBag.message = "Đã cập nhật lời tri ân khách hàng";
            GetWebResourceResult model = new GetWebResourceResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetWebResource("datnuocviet.trian").FirstOrDefault();
            }
            return View("TriAn", model);
        }

        public ActionResult EditComment(int id)
        {
            Comment model = new Comment();

            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.Comments.Single(p => p.CommentId == id);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult EditComment(Comment entity)
        {
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                Comment cm = db.Comments.Single(p => p.CommentId == entity.CommentId);

                cm.Author = entity.Author;
                cm.CommentContent = entity.CommentContent;
                cm.isDelete = entity.isDelete;

                db.SubmitChanges();
            }
            return RedirectToAction("Trian");
        }

        public ActionResult InsertComment()
        {
            return View();
        }

        [HttpPost]
        public ActionResult InsertComment(Comment entity)
        {
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.Comments.InsertOnSubmit(entity);
                db.SubmitChanges();
            }

            return RedirectToAction("Trian");
        }
        #endregion

        #region email
        [CustomAuthentication]
        public ActionResult EmailList()
        {
            List<GetEmailListResult> model = new List<GetEmailListResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetEmailList().ToList();
            }
            return View(model);
        }
        #endregion

        #region Gallery
        [CustomAuthentication]
        public ActionResult Gallery()
        {
            return View();
        }

        [CustomAuthentication]
        [HttpPost]
        public WrappedJsonResult UploadGallery(HttpPostedFileBase UploadImage1, FormCollection form)
        {
            if (Helper.TestImage(UploadImage1, 1024000, false) == false)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "Hình ảnh không đúng định dạng"
                    }
                };
            }
            string folderName = form["folderName1"];
            string title = form["title"].Trim();
            if (title == "")
                title = DateTime.Now.ToString();
            string physicalPath = Server.MapPath(Url.Content("~/Resource/" + folderName));
            string temp = Helper.SaveFile(UploadImage1, "~/Resource/" + folderName + "/", physicalPath);
            /*thumb*/
            string thumburl = temp.Replace("images/", "images/thumb/");
            var r = new ResizeSettings();
            r.Width = 230;
            r.Height = 173;
            r.Scale = ScaleMode.Both;
            r.Format = "jpg";
            ImageBuilder.Current.Build(temp, thumburl, r);
            /*end*/
            string TourId = form["Id1"];
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                db.InsertGallery(title, Url.Content(temp));
            }
            return new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    ImagePath = Url.Content(temp)
                }
            };
        }

        [CustomAuthentication]
        [HttpPost]
        public JsonResult GetGallery()
        {
            List<GetGalleryResult> model = new List<GetGalleryResult>();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GetGallery().ToList();
            }
            foreach (var item in model)
            {
                item.Image = Url.Content(item.Image.Replace("images/", "images/thumb/"));
            }
            return Json(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public JsonResult GalleryDetail(int id)
        {
            GalleryDetailResult model = new GalleryDetailResult();
            using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
            {
                model = db.GalleryDetail(id).SingleOrDefault();
                model.Image = Url.Content(model.Image);
            }
            return Json(model);
        }

        [CustomAuthentication]
        [HttpPost]
        public string GalleryUpdate(int id, bool deleted, string title)
        {
            try
            {
                using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                {
                    db.UpdateGallery(id, title, deleted);
                    if (deleted == true)
                        return "Đã xóa hình ảnh";
                    else
                        return "Cập nhật hình ảnh thành công";
                }
            }
            catch (Exception)
            {
                return "Lỗi!";
            }
        }
        #endregion

        #region UploadImage
        [CustomAuthentication]
        [HttpPost]
        public WrappedJsonResult UploadImage(HttpPostedFileBase UploadImage, FormCollection form)
        {
            if (Helper.TestImage(UploadImage, 1024000, false) == false)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "Hình ảnh không đúng định dạng"
                    }
                };
            }
            string folderName = form["folderName"];
            string physicalPath = Server.MapPath(Url.Content("~/Resource/" + folderName));
            string temp = Helper.SaveFile(UploadImage, "~/Resource/" + folderName + "/", physicalPath);
            return new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    ImagePath = Url.Content(temp)
                }
            };
        }

        [CustomAuthentication]
        [HttpPost]
        public WrappedJsonResult UploadImageWidthSave(HttpPostedFileBase UploadImage1, FormCollection form)
        {
            if (Helper.TestImage(UploadImage1, 1024000, false) == false)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "Hình ảnh không đúng định dạng"
                    }
                };
            }
            string folderName = form["folderName1"];
            string physicalPath = Server.MapPath(Url.Content("~/Resource/" + folderName));
            string temp = Helper.SaveFile(UploadImage1, "~/Resource/" + folderName + "/", physicalPath);
            /*thumb*/
            string thumburl = temp.Replace("images/","images/thumb/");
            var r = new ResizeSettings();
            r.Height = 145;
            r.Scale = ScaleMode.Both;
            r.Format = "jpg";
            ImageBuilder.Current.Build(temp, thumburl,r);
            /*end*/
            string TourId = form["Id1"];
                using (DatNuocVietDbDataContext db = new DatNuocVietDbDataContext())
                {
                    db.InsertTourImage(Convert.ToInt32(TourId), Url.Content(temp), 1);
                }
            return new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    ImagePath = Url.Content(temp)
                }
            };
        }

        [CustomAuthentication]
        [HttpPost]
        public WrappedJsonResult UploadImageWidthSave1(HttpPostedFileBase UploadImage1, FormCollection form)
        {
            if (Helper.TestImage(UploadImage1, 1024000, false) == false)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "Hình ảnh không đúng định dạng"
                    }
                };
            }
            string folderName = form["folderName1"];
            string physicalPath = Server.MapPath(Url.Content("~/Resource/" + folderName));
            string temp = Helper.SaveFile(UploadImage1, "~/Resource/" + folderName + "/", physicalPath);
            /*thumb*/
            string thumburl = temp.Replace("images/", "images/thumb/");
            var r = new ResizeSettings();
            r.Height = 83;
            r.Scale = ScaleMode.Both;
            r.Format = "jpg";
            ImageBuilder.Current.Build(temp, thumburl, r);
            /*end*/
            return new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    ImagePath = Url.Content(temp)
                }
            };
        }
        #endregion
    }
}
